<?php

declare(strict_types=1);

namespace Plugin\Attractions\AttractionManagement\Service;

use App\Exception\BusinessException;
use App\Http\Common\ResultCode;
use Common\Common;
use Hyperf\DbConnection\Db;
use Hyperf\Di\Annotation\Inject;
use Plugin\Attractions\AttractionManagement\Repository\AttractionInfoRepository;
use Plugin\Attractions\AttractionManagement\Repository\AttractionInfoTagRepository;
use Plugin\Attractions\AttractionManagement\Repository\AttractionTypeRepository;

class InfoService
{
    #[Inject]
    private AttractionInfoRepository $repository;
    #[Inject]
    private AttractionTypeRepository $typeRepository;
    #[inject]
    private AttractionInfoTagRepository $tagsRepository;

    public function list(array $params): array
    {
        return $this->repository->showListPage($params);
    }



    public function create(array $data): array
    {
        if (!$this->typeRepository->isValidType($data['typeId'])) {
            throw new BusinessException(ResultCode::UNPROCESSABLE_ENTITY, trans('attraction-management.info.notType'));
        }

        if (isset($data['startTime']) && isset($data['endTime']) && strtotime($data['startTime']) > strtotime($data['endTime'])) {
            throw new BusinessException(ResultCode::UNPROCESSABLE_ENTITY, trans('attraction-management.timeError'));
        }
        Db::beginTransaction();
        try {
            $res = $this->repository->create([
                'title' => $data['title'],
                'intro' => $data['intro'] ?? '',
                'group' => $data['group'],
                'type_id' => $data['typeId'],
                'spot_id' => $data['spotId'] ?? 0,
                'status' => $data['status'] ?? 3,
                'cover_id' => $data['coverId'] ?? '',
                'sort' => $data['sort'] ?? 100,
                'start_time' => $data['startTime'] ?? '0000-00-00 00:00:00',
                'end_time' => $data['endTime'] ?? '0000-00-00 00:00:00',
                'extension' => $data['extension'] ?? [],
            ]);
            if (isset($data['tags'])) {
                $this->tagsRepository->insert($data['tags'], $res->id);
            }
            Db::commit();
            return $res->toArray();
        } catch (\Throwable $e) {
            Db::rollback();
            Common::logException(__CLASS__, $e);
            return [];
        }
    }

    public function delete(array $id): int
    {
        $coverId = $this->repository->getQuery()->whenIn('id', $id)->pluck('cover_id')->toArray();
        Db::beginTransaction();
        try {
            // 删除信息
            $res = $this->repository->deleteById($id);
            // 删除标签
            $this->tagsRepository->getQuery()->whereIn('info_id', $id)->delete();
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            Common::logException(__CLASS__, $e);
            return 0;
        }
        return $res;
    }

    public function update(int $id, array $data): bool
    {
        if (isset($data['startTime']) && isset($data['endTime']) && strtotime($data['startTime']) > strtotime($data['endTime'])) {
            throw new BusinessException(ResultCode::UNPROCESSABLE_ENTITY, trans('attraction-management.timeError'));
        }
        Db::beginTransaction();
        try {
            $updateData = [];
            foreach ($data as $key => $value){
                $updateData[strtolower(preg_replace('/(?<!^)[A-Z]/', '_$0', $key))] = $value;
            }
            $res = $this->repository->updateById($id, $updateData);
            Db::commit();
        } catch (\Throwable $e) {
            Db::rollBack();
            Common::logException(__CLASS__, $e);
            return false;
        }
        return $res;
    }

    public function get(int $id): array
    {
        return $this->repository->getDetail($id);
    }

    public function listValidInfos($params)
    {
        return $this->repository->isValidInfo($params);
    }
}